package com.example.stock.util;

import cn.hutool.core.collection.CollectionUtil;
import com.example.stock.comm.StrategyEnum;
import com.example.stock.entity.eo.StockStatEo;
import com.example.stock.entity.service.IStockStatService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@EnableScheduling
@EnableAsync
public class StockStatUtil {

    @Resource
    private IStockStatService IStockStatService;


    private int startStatistics = 0;
    public void startStatistics() {
        if (startStatistics > 0) {
            throw new RuntimeException("repeat!");
        }
        startStatistics++;
    }

    private List<StockStatEo> allStatEos = new ArrayList<>();
    public void recordAll(int mm, int nn, Double finalMoney, Double ext1, String tsCode, StrategyEnum strategy){
        allStatEos.add(new StockStatEo()
                .setM(mm)
                .setN(nn)
                .setMoney(finalMoney)
                .setExt1(ext1)
                .setTsCode(tsCode)
                .setStrategy(strategy.name())
        );

        if (allStatEos.size() == 100) {
            String uuid = UUID.randomUUID().toString();
            asyncSave(allStatEos,uuid);
            System.out.println("sync save batch: " + uuid);
            allStatEos = new ArrayList<>();
        }

    }
    public void finishRecordAll(){
        if (allStatEos.size() >0) {
            String uuid = UUID.randomUUID().toString();
            asyncSave(allStatEos,uuid);
            System.out.println("sync save batch: " + uuid);
            allStatEos = new ArrayList<>();
        }
    }

    @Async
    public void asyncSave(List<StockStatEo> allStatEos,String uuid) {
        IStockStatService.saveBatch(allStatEos);
        System.out.println("finish save batch: " + uuid);
    }

    public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
        //判断集合是否为空
        if (CollectionUtil.isEmpty(list))
            return Collections.emptyList();
        //计算分割后的大小
        int maxSize = (list.size() + splitSize - 1) / splitSize;
        //开始分割
        return Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .parallel()
                .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toList());
    }
}
